<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label="法人行" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                <a-select v-if="this.user.admin" mode="default" :allowClear="true" style="width: 100%"
                  @change="handleInstChange" v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{ r.label }}-{{ r.value }}</a-select-option>
                </a-select>
                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId"
                  :disabled="true" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="queryParams.instId != ''">
              <a-form-item label="公告标题" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                <a-input v-model="queryParams.title" />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="padding-left: 455px; align: center" v-show="queryParams.instId != ''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </span>
      </a-form>
    </div>
    <div v-show="queryParams.instId != ''">
      <div class="operator">
        <a-button v-hasPermission="['notify:add']" ghost type="primary" @click="add">新增</a-button>
        <a-button v-hasPermission="['notify:delete']" @click="batchDelete">删除</a-button>

      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo" :columns="columns" :rowKey="record => record.id" :dataSource="dataSource"
        :pagination="pagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :scroll="{ x: 900 }"
        @change="handleTableChange">
        <template slot="remark" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div style="max-width: 200px">{{ text }}</div>
            </template>
            <p style="width: 200px;margin-bottom: 0">{{ text }}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="['notify:update']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
            @click="edit(record)" title="修改角色"></a-icon>
          &nbsp;
          <a-icon type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
        </template>
      </a-table>
      <!-- 角色信息查看 -->
      <!-- roleInfoVisiable于弹框页的visiable的值要一样 传数据要加this-->
      <notity-info @close="handleRoleInfoClose" :roleInfoVisiable="notityInfo.visiable"
        :notityInfoData="notityInfo.data" :roleInstId="queryParams.instId" ref="NotityInfo">
      </notity-info>
      <!-- 新增角色 -->
      <notity-info-add @close="handleRoleAddClose" @success="handleRoleAddSuccess"
        :roleAddVisiable="NotityInfoAdd.visiable" :roleInstId="queryParams.instId" :roleCodeData="roleCodeData">
      </notity-info-add>

      <!-- 修改角色 -->
      <notity-info-edit ref="NotityInfoEdit" :NotityInfoEditData="this.NotityInfoEdit.data" @close="handleRoleEditClose"
        @success="handleRoleEditSuccess" @clearExpireTime="clearExpireTime" :notityEditVisiable="NotityInfoEdit.visiable" :roleInstId="queryParams.instId">
      </notity-info-edit>
    </div>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import NotityInfo from './NotityInfo'
import NotityInfoEdit from './NotityEdit'
import { mapState } from "vuex"
import NotityInfoAdd from './NotityInfoAdd'

export default {
  name: 'notifyInfo',
  // components: {RangeDate, NotityInfovue, NotityInfoEdit,NotityInfoAdd},
  components: { RangeDate, NotityInfo, NotityInfoEdit, NotityInfoAdd },
  data() {
    return {
      advanced: false,
      notityInfo: {
        visiable: false,
        data: {}
      },
      NotityInfoAdd: {
        visiable: false
      },
      NotityInfoEdit: {
        visiable: false,
        data: {}
      },
      userInfo: {
        visiable: false,
      },
      queryParams: {
        createTimeFrom: '',
        createTimeTo: '',
        instId: ''
      },
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      selectedRowKeys: [],
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      instIdData: [],
      roleCodeData: []
    }
  },
  computed: {
    ...mapState({
      user: state => state.account.user,
      userRoleList: state => state.account.roles
    }),
    //分页字段内容
    columns() {
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      let { filteredInfo } = this
      filteredInfo = filteredInfo || {}
      return [{
        title: '法人行',
        dataIndex: 'instId',



        filterMultiple: false,
        filteredValue: filteredInfo.roleCode || null,
        onFilter: (value, record) => record.roleCode.includes(value)
      }, {
        title: '公告标题',
        dataIndex: 'title'
      }, {
        title: '公告开始日期',
        dataIndex: 'beginTime',

        // filterMultiple: false,
        // filteredValue: filteredInfo.type || null,
        // onFilter: (value, record) => record.type.includes(value)
      }, {
        title: '公告有效期',
        dataIndex: 'expireTime',
        scopedSlots: { customRender: 'roleDesc' },

      }, {
        title: '状态',
        dataIndex: 'notifyStatus',
        customRender: (text, row, index) => {
          switch (text) {
            case '01':
              return <a-tag color="cyan"> 发布</a-tag>
            case '00':
              return <a-tag color="pink"> 未发布 </a-tag>
            default:
              return text
          }
        },
        filters: [
          { text: ' 发布', value: '01' },
          { text: '未发布', value: '00' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.notifyStatus || null,
        onFilter: (value, record) => record.notifyStatus.includes(value)
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        sorter: (a, b) => { return a.createTime > b.createTime ? 1 : -1 }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  //查询法人号
  mounted() {
    this.$get('admin/upmporg/getInstList').then((r) => {
      this.instIdData = r.data
    })
    if (!this.user.admin) {
      this.$set(this.queryParams, "instId", this.user.instId);
      this.search();
    }
  },
  methods: {
    clearExpireTime(){
      this.NotityInfoEdit.data.expireTime=''
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    add() {
      this.NotityInfoAdd.visiable = true
    },
    // 条件查询
    handleInstChange(value) {
      this.queryParams.instId = value;
      if (value != "") {
        this.$get('admin/upmprole/getRoleCode/' + value + '/add').then((r) => {
          this.roleCodeData = r.data;
          this.search();
        })
      }
    },
    handleRoleAddClose() {
      this.NotityInfoAdd.visiable = false
    },
    handleRoleAddSuccess() {
      this.NotityInfoAdd.visiable = false
      this.$message.success('新增公告成功')
      this.search()
    },
    view(record) {
      this.$get('gen/tbnotifyinfo/notifyInfo/' + record.id).then((r) => {
        this.notityInfo.data = r.data
      })

      this.notityInfo.visiable = true
    },
    handleRoleInfoClose() {
      this.notityInfo.visiable = false
    },
    edit(record) {
      this.$get('gen/tbnotifyinfo/notifyInfo/' + record.id).then((r) => {
        this.NotityInfoEdit.data = r.data
        console.log(this.NotityInfoEdit.data);
      })
      this.NotityInfoEdit.visiable = true;
    },
    handleRoleEditSuccess() {
      this.NotityInfoEdit.visiable = false
      this.$message.success('修改公告成功')
      this.search()
    },
    handleRoleEditClose() {
      //弹框退出
      this.NotityInfoEdit.visiable = false
    },
    handleDateChange(value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    batchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk() {
          let NotifyIds = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          NotifyIds.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.id + ',') > -1 }).map(m => { return m.id }))
          that.$delete('gen/tbnotifyinfo/' + NotifyIds.join(',')).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message)
              that.selectedRowKeys = []
              that.search()
            } else {
              that.$message.error(res.data.message)
            }
          })
        },
        onCancel() {
          that.selectedRowKeys = []
        }
      })
    },
    search() {
      // console.log(sortedInfo);
      let { sortedInfo } = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    reset() {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      // 清空时间选择
      this.$refs.createTime.reset()

      if (!this.user.admin) {
        this.$set(this.queryParams, "instId", this.user.instId);
        this.search();
      }
    },
    handleTableChange(pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.userInfo.visiable = false
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch(params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      params.instId = this.queryParams.instId
      this.$get('gen/tbnotifyinfo', {//
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        //总条数
        pagination.total = data.total
        //分页的内容
        this.dataSource = data.rows
        this.pagination = pagination
        this.loading = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>

